agora inbox for [email protected]  
help / color / mirror / Atom feed
[PATCH] Teach REPACK to upgrade its lock safely.
968+ messages / 2 participants
[nested] [flat]

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH] Teach REPACK to upgrade its lock safely.
@ 2026-04-14 09:59  Antonin Houska <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Antonin Houska @ 2026-04-14 09:59 UTC (permalink / raw)

REPACK (CONCURRENTLY) needs to upgrade its ShareUpdateExclusiveLock (SUEL) to
AccessExclusiveLock at the end of table processing. If another session, which
already has a non-conflicting lock on the table, tried to get SUEL too, it
would end up in a deadlock with REPACK. Such situation does not hurt as long
as the deadlock detector choses to terminate the other session, but it's
possible that it terminates REPACK. A lot of REPACK's work would be wasted
this way.

This patch checks for such situation, and if the other session tries to get
the SUEL, it receives a deadlock report before it actually starts waiting.

Please note that the other session can safely run VACUUM w/o receiving the
deadlock report. The point is that VACUUM cannot run in a transaction block,
so the session cannot have any other lock when trying to get SUEL on the
table. In that case, REPACK gets its AccessExclusiveLock first, even if VACUUM
requested SUEL earlier. VACUUM then just needs wait for REPACK to finish, and
then it can start.
---
 src/backend/commands/repack.c                 | 25 +++++++-
 src/backend/storage/lmgr/deadlock.c           | 10 ++--
 src/backend/storage/lmgr/lock.c               | 30 ++++++++++
 src/backend/storage/lmgr/proc.c               | 55 ++++++++++++++++-
 src/include/storage/lock.h                    |  5 +-
 src/include/storage/proc.h                    |  6 +-
 .../injection_points/expected/repack.out      | 59 ++++++++++++++++++-
 .../injection_points/specs/repack.spec        | 29 +++++++++
 8 files changed, 209 insertions(+), 10 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index 58e3867246f..e9193067666 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -285,6 +285,18 @@ ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel)
 		 * to understand and we don't lose any functionality.
 		 */
 		PreventInTransactionBlock(isTopLevel, "REPACK (CONCURRENTLY)");
+
+		/*
+		 * Also set the PROC_IN_CONCURRENT_REPACK flag.  This makes the lock
+		 * manager cause anyone that would conflict with us to error out.
+		 * It's important to set this flag ahead of actually locking the
+		 * relation; it won't of course affect anyone until we do have a lock
+		 * that others can conflict with.
+		 */
+		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+		MyProc->statusFlags |= PROC_IN_CONCURRENT_REPACK;
+		ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+		LWLockRelease(ProcArrayLock);
 	}
 
 	/*
@@ -3086,7 +3098,18 @@ rebuild_relation_finish_concurrent(Relation NewHeap, Relation OldHeap,
 		LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
 
 	/*
-	 * Tuples and pages of the old heap will be gone, but the heap will stay.
+	 * Now that we have all access-exclusive locks on all relations, we no
+	 * longer want other processes to error out when trying to acquire a
+	 * conflicting lock.  Therefore, unset our flag.
+	 */
+	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
+	MyProc->statusFlags &= ~PROC_IN_CONCURRENT_REPACK;
+	ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
+	LWLockRelease(ProcArrayLock);
+
+	/*
+	 * Tuples and pages of the old heap will be gone, but the heap itself will
+	 * stay.
 	 */
 	TransferPredicateLocksToHeapRelation(OldHeap);
 	foreach_ptr(RelationData, index, indexrels)
diff --git a/src/backend/storage/lmgr/deadlock.c b/src/backend/storage/lmgr/deadlock.c
index b8962d875b6..3772a7aa3df 100644
--- a/src/backend/storage/lmgr/deadlock.c
+++ b/src/backend/storage/lmgr/deadlock.c
@@ -1146,8 +1146,10 @@ DeadLockReport(void)
 void
 RememberSimpleDeadLock(PGPROC *proc1,
 					   LOCKMODE lockmode,
-					   LOCK *lock,
-					   PGPROC *proc2)
+					   LOCK *lock, /* XXX Only lockmode? */
+					   PGPROC *proc2,
+					   LOCKMODE lockmode2,
+					   LOCKTAG *locktag2)
 {
 	DEADLOCK_INFO *info = &deadlockDetails[0];
 
@@ -1155,8 +1157,8 @@ RememberSimpleDeadLock(PGPROC *proc1,
 	info->lockmode = lockmode;
 	info->pid = proc1->pid;
 	info++;
-	info->locktag = proc2->waitLock->tag;
-	info->lockmode = proc2->waitLockMode;
+	info->locktag = *locktag2;
+	info->lockmode = lockmode2;
 	info->pid = proc2->pid;
 	nDeadlockDetails = 2;
 }
diff --git a/src/backend/storage/lmgr/lock.c b/src/backend/storage/lmgr/lock.c
index c221fe96889..44aa2ca26a7 100644
--- a/src/backend/storage/lmgr/lock.c
+++ b/src/backend/storage/lmgr/lock.c
@@ -674,6 +674,36 @@ LockHeldByMe(const LOCKTAG *locktag,
 	return false;
 }
 
+/*
+ * HaveRelLock -- test whether the current backend has a fast path lock on
+ *		the relation in any mode.
+ */
+bool
+HaveFastPathLock(Oid relid)
+{
+	uint32		group = FAST_PATH_REL_GROUP(relid);
+	bool		result = false;
+
+	LWLockAcquire(&MyProc->fpInfoLock, LW_SHARED);
+	for (int i = 0; i < FP_LOCK_SLOTS_PER_GROUP; i++)
+	{
+		uint32		f = FAST_PATH_SLOT(group, i);
+		uint32		lockmask;
+
+		if (relid != MyProc->fpRelId[f])
+			continue;
+		lockmask = FAST_PATH_GET_BITS(MyProc, f);
+		if (lockmask)
+		{
+			result = true;
+			break;
+		}
+	}
+	LWLockRelease(&MyProc->fpInfoLock);
+
+	return result;
+}
+
 #ifdef USE_ASSERT_CHECKING
 /*
  * GetLockMethodLocalHash -- return the hash of local locks, for modules that
diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c
index 1ac25068d62..3d47b1284a3 100644
--- a/src/backend/storage/lmgr/proc.c
+++ b/src/backend/storage/lmgr/proc.c
@@ -1156,6 +1156,7 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 	LOCKMASK	myHeldLocks;
 	bool		early_deadlock = false;
 	PGPROC	   *leader = MyProc->lockGroupLeader;
+	bool		check_repack = false;
 
 	Assert(LWLockHeldByMeInMode(partitionLock, LW_EXCLUSIVE));
 
@@ -1193,6 +1194,56 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 		}
 	}
 
+	/*
+	 * If I am already holding this lock (in any mode) and trying to get
+	 * ShareUpdateExclusiveLock (or higher), check if REPACK (CONCURRENTLY) is
+	 * already holding ShareUpdateExclusiveLock. The problem is if that by
+	 * trying to upgrade the lock to AccessExclusiveLock it would get into a
+	 * deadlock with us.
+	 */
+	if (lock->tag.locktag_type == LOCKTAG_RELATION &&
+		lock->tag.locktag_field1 == MyDatabaseId &&
+		lockmode >= ShareUpdateExclusiveLock)
+	{
+		if (myHeldLocks > 0 ||
+			HaveFastPathLock(lock->tag.locktag_field2))
+			check_repack = true;
+	}
+	if (check_repack)
+	{
+		dlist_iter	iter;
+
+		dlist_foreach(iter, &lock->procLocks)
+		{
+			PROCLOCK   *otherproclock;
+			PGPROC		*otherproc;
+
+			otherproclock = dlist_container(PROCLOCK, lockLink, iter.cur);
+			otherproc = otherproclock->tag.myProc;
+			if (otherproc != MyProc &&
+				otherproc->statusFlags & PROC_IN_CONCURRENT_REPACK)
+			{
+				LOCKMASK	repackmask = otherproclock->holdMask;
+
+				/*
+				 * Is REPACK already holding ShareUpdateExclusiveLock?
+				 */
+				if ((repackmask & LOCKBIT_ON(ShareUpdateExclusiveLock)) != 0)
+				{
+					/*
+					 * There should be no more than one REPACK working on
+					 * particular table, so let's error out.
+					 */
+					RememberSimpleDeadLock(MyProc, lockmode, lock,
+										   otherproc,
+										   ShareUpdateExclusiveLock,
+										   &otherproclock->tag.myLock->tag);
+					return PROC_WAIT_STATUS_ERROR;
+				}
+			}
+		}
+	}
+
 	/*
 	 * Determine where to add myself in the wait queue.
 	 *
@@ -1240,7 +1291,9 @@ JoinWaitQueue(LOCALLOCK *locallock, LockMethod lockMethodTable, bool dontWait)
 					 * a flag to check below, and break out of loop.  Also,
 					 * record deadlock info for later message.
 					 */
-					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
+					RememberSimpleDeadLock(MyProc, lockmode, lock, proc,
+										   proc->waitLockMode,
+										   &proc->waitLock->tag);
 					early_deadlock = true;
 					break;
 				}
diff --git a/src/include/storage/lock.h b/src/include/storage/lock.h
index ee3cb1dc203..85804d61ce9 100644
--- a/src/include/storage/lock.h
+++ b/src/include/storage/lock.h
@@ -401,6 +401,7 @@ extern void LockReleaseCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern void LockReassignCurrentOwner(LOCALLOCK **locallocks, int nlocks);
 extern bool LockHeldByMe(const LOCKTAG *locktag,
 						 LOCKMODE lockmode, bool orstronger);
+extern bool HaveFastPathLock(Oid relid);
 #ifdef USE_ASSERT_CHECKING
 extern HTAB *GetLockMethodLocalHash(void);
 #endif
@@ -440,7 +441,9 @@ pg_noreturn extern void DeadLockReport(void);
 extern void RememberSimpleDeadLock(PGPROC *proc1,
 								   LOCKMODE lockmode,
 								   LOCK *lock,
-								   PGPROC *proc2);
+								   PGPROC *proc2,
+								   LOCKMODE lockmode2,
+								   LOCKTAG *locktag2);
 extern void InitDeadLockChecking(void);
 
 extern int	LockWaiterCount(const LOCKTAG *locktag);
diff --git a/src/include/storage/proc.h b/src/include/storage/proc.h
index 3e1d1fad5f9..76c6bb44251 100644
--- a/src/include/storage/proc.h
+++ b/src/include/storage/proc.h
@@ -70,10 +70,12 @@ struct XidCache
 #define		PROC_AFFECTS_ALL_HORIZONS	0x20	/* this proc's xmin must be
 												 * included in vacuum horizons
 												 * in all databases */
+#define		PROC_IN_CONCURRENT_REPACK	0x40	/* REPACK (CONCURRENTLY) */
 
-/* flags reset at EOXact */
+/* flags reset at EOXact.  A bit of a misnomer ... */
 #define		PROC_VACUUM_STATE_MASK \
-	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND)
+	(PROC_IN_VACUUM | PROC_IN_SAFE_IC | PROC_VACUUM_FOR_WRAPAROUND | \
+	 PROC_IN_CONCURRENT_REPACK)
 
 /*
  * Xmin-related flags. Make sure any flags that affect how the process' Xmin
diff --git a/src/test/modules/injection_points/expected/repack.out b/src/test/modules/injection_points/expected/repack.out
index b575e9052ee..960044776f4 100644
--- a/src/test/modules/injection_points/expected/repack.out
+++ b/src/test/modules/injection_points/expected/repack.out
@@ -1,4 +1,4 @@
-Parsed test spec with 2 sessions
+Parsed test spec with 3 sessions
 
 starting permutation: wait_before_lock change_existing change_new change_subxact1 change_subxact2 check2 wakeup_before_lock check1
 injection_points_attach
@@ -111,3 +111,60 @@ injection_points_detach
                        
 (1 row)
 
+
+starting permutation: check1_relnode_only wait_before_lock lock3 wakeup_before_lock check1_relnode_only
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    1
+(1 row)
+
+step wait_before_lock: 
+	REPACK (CONCURRENTLY) repack_test USING INDEX repack_test_pkey;
+ <waiting ...>
+step lock3: 
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+
+i|j
+-+-
+1|1
+(1 row)
+
+ERROR:  deadlock detected
+step wakeup_before_lock: 
+	SELECT injection_points_wakeup('repack-concurrently-before-lock');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step wait_before_lock: <... completed>
+step check1_relnode_only: 
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+
+count
+-----
+    2
+(1 row)
+
+injection_points_detach
+-----------------------
+                       
+(1 row)
+
diff --git a/src/test/modules/injection_points/specs/repack.spec b/src/test/modules/injection_points/specs/repack.spec
index d727a9b056b..5ffcb558718 100644
--- a/src/test/modules/injection_points/specs/repack.spec
+++ b/src/test/modules/injection_points/specs/repack.spec
@@ -55,6 +55,13 @@ step check1
 	FROM data_s1 d1 FULL JOIN data_s2 d2 USING (i, j)
 	WHERE d1.i ISNULL OR d2.i ISNULL;
 }
+step check1_relnode_only
+{
+	INSERT INTO relfilenodes(node)
+	SELECT relfilenode FROM pg_class WHERE relname='repack_test';
+
+	SELECT count(DISTINCT node) FROM relfilenodes;
+}
 teardown
 {
 	SELECT injection_points_detach('repack-concurrently-before-lock');
@@ -129,6 +136,20 @@ step wakeup_before_lock
 	SELECT injection_points_wakeup('repack-concurrently-before-lock');
 }
 
+session s3
+# Try to acquire SharedUpdateExclusiveLock on a table while REPACK is already
+# holding it and before it tries to upgrade it to AccessExclusiveLock. Since
+# this session is already holding another lock no the table, REPACK cannot
+# resolve the problem by getting ahead in the wait queue. The solution is that
+# the LOCK TABLE triggers a deadlock report. The deadlock does not actually
+# take place, but it would if this session started to wait.
+step lock3
+{
+	BEGIN;
+	SELECT * FROM repack_test ORDER BY i LIMIT 1;
+	LOCK TABLE repack_test IN SHARE UPDATE EXCLUSIVE MODE;
+}
+
 # Test if data changes introduced while one session is performing REPACK
 # CONCURRENTLY find their way into the table.
 permutation
@@ -140,3 +161,11 @@ permutation
 	check2
 	wakeup_before_lock
 	check1
+
+# See 'lock3' above. We check relnodes to make sure that REPACK finished.
+permutation
+	check1_relnode_only
+	wait_before_lock
+	lock3
+	wakeup_before_lock
+	check1_relnode_only
-- 
2.47.3


--=-=-=--





^ permalink  raw  reply  [nested|flat] 968+ messages in thread

* [PATCH v4 3/4] psql: bump minimum supported version to v10
@ 2026-04-17 18:34  Nathan Bossart <[email protected]>
  0 siblings, 0 replies; 968+ messages in thread

From: Nathan Bossart @ 2026-04-17 18:34 UTC (permalink / raw)

---
 doc/src/sgml/ref/psql-ref.sgml |   2 +-
 src/bin/psql/command.c         |  23 +---
 src/bin/psql/describe.c        | 244 +--------------------------------
 3 files changed, 11 insertions(+), 258 deletions(-)

diff --git a/doc/src/sgml/ref/psql-ref.sgml b/doc/src/sgml/ref/psql-ref.sgml
index 7c05afd4719..56c2692e618 100644
--- a/doc/src/sgml/ref/psql-ref.sgml
+++ b/doc/src/sgml/ref/psql-ref.sgml
@@ -5523,7 +5523,7 @@ PSQL_EDITOR_LINENUMBER_ARG='--line '
        or an older major version.  Backslash commands are particularly likely
        to fail if the server is of a newer version than <application>psql</application>
        itself.  However, backslash commands of the <literal>\d</literal> family should
-       work with servers of versions back to 9.2, though not necessarily with
+       work with servers of versions back to 10, though not necessarily with
        servers newer than <application>psql</application> itself.  The general
        functionality of running SQL commands and displaying query results
        should also work with servers of a newer major version, but this cannot
diff --git a/src/bin/psql/command.c b/src/bin/psql/command.c
index 01b8f11aadd..44ef11d980e 100644
--- a/src/bin/psql/command.c
+++ b/src/bin/psql/command.c
@@ -4471,10 +4471,10 @@ connection_warnings(bool in_startup)
 
 		/*
 		 * Warn if server's major version is newer than ours, or if server
-		 * predates our support cutoff (currently 9.2).
+		 * predates our support cutoff (currently 10).
 		 */
 		if (pset.sversion / 100 > client_ver / 100 ||
-			pset.sversion < 90200)
+			pset.sversion < 100000)
 			printf(_("WARNING: %s major version %s, server major version %s.\n"
 					 "         Some psql features might not work.\n"),
 				   pset.progname,
@@ -6278,15 +6278,13 @@ get_create_object_cmd(EditableObjectType obj_type, Oid oid,
 			 * ensure the right view gets replaced.  Also, check relation kind
 			 * to be sure it's a view.
 			 *
-			 * Starting with PG 9.4, views may have WITH [LOCAL|CASCADED]
+			 * Views may have WITH [LOCAL|CASCADED]
 			 * CHECK OPTION.  These are not part of the view definition
 			 * returned by pg_get_viewdef() and so need to be retrieved
-			 * separately.  Materialized views (introduced in 9.3) may have
+			 * separately.  Materialized views may have
 			 * arbitrary storage parameter reloptions.
 			 */
 			printfPQExpBuffer(query, "/* %s */\n", _("Get view's definition and details"));
-			if (pset.sversion >= 90400)
-			{
 				appendPQExpBuffer(query,
 								  "SELECT nspname, relname, relkind, "
 								  "pg_catalog.pg_get_viewdef(c.oid, true), "
@@ -6297,19 +6295,6 @@ get_create_object_cmd(EditableObjectType obj_type, Oid oid,
 								  "LEFT JOIN pg_catalog.pg_namespace n "
 								  "ON c.relnamespace = n.oid WHERE c.oid = %u",
 								  oid);
-			}
-			else
-			{
-				appendPQExpBuffer(query,
-								  "SELECT nspname, relname, relkind, "
-								  "pg_catalog.pg_get_viewdef(c.oid, true), "
-								  "c.reloptions AS reloptions, "
-								  "NULL AS checkoption "
-								  "FROM pg_catalog.pg_class c "
-								  "LEFT JOIN pg_catalog.pg_namespace n "
-								  "ON c.relnamespace = n.oid WHERE c.oid = %u",
-								  oid);
-			}
 			break;
 	}
 
diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c
index 7f9b2b71a36..ec9c61ee924 100644
--- a/src/bin/psql/describe.c
+++ b/src/bin/psql/describe.c
@@ -3,9 +3,9 @@
  *
  * Support for the various \d ("describe") commands.  Note that the current
  * expectation is that all functions in this file will succeed when working
- * with servers of versions 9.2 and up.  It's okay to omit irrelevant
+ * with servers of versions 10 and up.  It's okay to omit irrelevant
  * information for an old server, but not to fail outright.  (But failing
- * against a pre-9.2 server is allowed.)
+ * against a pre-10 server is allowed.)
  *
  * Copyright (c) 2000-2026, PostgreSQL Global Development Group
  *
@@ -154,16 +154,6 @@ describeAccessMethods(const char *pattern, bool verbose)
 	printQueryOpt myopt = pset.popt;
 	static const bool translate_columns[] = {false, true, false, false};
 
-	if (pset.sversion < 90600)
-	{
-		char		sverbuf[32];
-
-		pg_log_error("The server (version %s) does not support access methods.",
-					 formatPGVersionNumber(pset.sversion, false,
-										   sverbuf, sizeof(sverbuf)));
-		return true;
-	}
-
 	initPQExpBuffer(&buf);
 
 	printfPQExpBuffer(&buf, "/* %s */\n", _("Get matching access methods"));
@@ -312,9 +302,6 @@ describeFunctions(const char *functypes, const char *func_pattern,
 	printQueryOpt myopt = pset.popt;
 	static const bool translate_columns[] = {false, false, false, false, true, true, true, false, true, true, false, false, false, false};
 
-	/* No "Parallel" column before 9.6 */
-	static const bool translate_columns_pre_96[] = {false, false, false, false, true, true, false, true, true, false, false, false, false};
-
 	if (strlen(functypes) != strspn(functypes, df_options))
 	{
 		pg_log_error("\\df only takes [%s] as options", df_options);
@@ -400,7 +387,6 @@ describeFunctions(const char *functypes, const char *func_pattern,
 						  gettext_noop("stable"),
 						  gettext_noop("volatile"),
 						  gettext_noop("Volatility"));
-		if (pset.sversion >= 90600)
 			appendPQExpBuffer(&buf,
 							  ",\n CASE\n"
 							  "  WHEN p.proparallel = "
@@ -613,16 +599,8 @@ describeFunctions(const char *functypes, const char *func_pattern,
 
 	myopt.title = _("List of functions");
 	myopt.translate_header = true;
-	if (pset.sversion >= 90600)
-	{
 		myopt.translate_columns = translate_columns;
 		myopt.n_translate_columns = lengthof(translate_columns);
-	}
-	else
-	{
-		myopt.translate_columns = translate_columns_pre_96;
-		myopt.n_translate_columns = lengthof(translate_columns_pre_96);
-	}
 
 	printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
 
@@ -1108,38 +1086,6 @@ permissionsList(const char *pattern, bool showSystem)
 					  "  ), E'\\n') AS \"%s\"",
 					  gettext_noop("Column privileges"));
 
-	if (pset.sversion >= 90500 && pset.sversion < 100000)
-		appendPQExpBuffer(&buf,
-						  ",\n  pg_catalog.array_to_string(ARRAY(\n"
-						  "    SELECT polname\n"
-						  "    || CASE WHEN polcmd != '*' THEN\n"
-						  "           E' (' || polcmd::pg_catalog.text || E'):'\n"
-						  "       ELSE E':'\n"
-						  "       END\n"
-						  "    || CASE WHEN polqual IS NOT NULL THEN\n"
-						  "           E'\\n  (u): ' || pg_catalog.pg_get_expr(polqual, polrelid)\n"
-						  "       ELSE E''\n"
-						  "       END\n"
-						  "    || CASE WHEN polwithcheck IS NOT NULL THEN\n"
-						  "           E'\\n  (c): ' || pg_catalog.pg_get_expr(polwithcheck, polrelid)\n"
-						  "       ELSE E''\n"
-						  "       END"
-						  "    || CASE WHEN polroles <> '{0}' THEN\n"
-						  "           E'\\n  to: ' || pg_catalog.array_to_string(\n"
-						  "               ARRAY(\n"
-						  "                   SELECT rolname\n"
-						  "                   FROM pg_catalog.pg_roles\n"
-						  "                   WHERE oid = ANY (polroles)\n"
-						  "                   ORDER BY 1\n"
-						  "               ), E', ')\n"
-						  "       ELSE E''\n"
-						  "       END\n"
-						  "    FROM pg_catalog.pg_policy pol\n"
-						  "    WHERE polrelid = c.oid), E'\\n')\n"
-						  "    AS \"%s\"",
-						  gettext_noop("Policies"));
-
-	if (pset.sversion >= 100000)
 		appendPQExpBuffer(&buf,
 						  ",\n  pg_catalog.array_to_string(ARRAY(\n"
 						  "    SELECT polname\n"
@@ -1666,7 +1612,7 @@ describeOneTableDetails(const char *schemaname,
 						   : "''"),
 						  oid);
 	}
-	else if (pset.sversion >= 100000)
+	else
 	{
 		appendPQExpBuffer(&buf,
 						  "SELECT c.relchecks, c.relkind, c.relhasindex, c.relhasrules, "
@@ -1683,57 +1629,6 @@ describeOneTableDetails(const char *schemaname,
 						   : "''"),
 						  oid);
 	}
-	else if (pset.sversion >= 90500)
-	{
-		appendPQExpBuffer(&buf,
-						  "SELECT c.relchecks, c.relkind, c.relhasindex, c.relhasrules, "
-						  "c.relhastriggers, c.relrowsecurity, c.relforcerowsecurity, "
-						  "c.relhasoids, false as relispartition, %s, c.reltablespace, "
-						  "CASE WHEN c.reloftype = 0 THEN '' ELSE c.reloftype::pg_catalog.regtype::pg_catalog.text END, "
-						  "c.relpersistence, c.relreplident\n"
-						  "FROM pg_catalog.pg_class c\n "
-						  "LEFT JOIN pg_catalog.pg_class tc ON (c.reltoastrelid = tc.oid)\n"
-						  "WHERE c.oid = '%s';",
-						  (verbose ?
-						   "pg_catalog.array_to_string(c.reloptions || "
-						   "array(select 'toast.' || x from pg_catalog.unnest(tc.reloptions) x), ', ')\n"
-						   : "''"),
-						  oid);
-	}
-	else if (pset.sversion >= 90400)
-	{
-		appendPQExpBuffer(&buf,
-						  "SELECT c.relchecks, c.relkind, c.relhasindex, c.relhasrules, "
-						  "c.relhastriggers, false, false, c.relhasoids, "
-						  "false as relispartition, %s, c.reltablespace, "
-						  "CASE WHEN c.reloftype = 0 THEN '' ELSE c.reloftype::pg_catalog.regtype::pg_catalog.text END, "
-						  "c.relpersistence, c.relreplident\n"
-						  "FROM pg_catalog.pg_class c\n "
-						  "LEFT JOIN pg_catalog.pg_class tc ON (c.reltoastrelid = tc.oid)\n"
-						  "WHERE c.oid = '%s';",
-						  (verbose ?
-						   "pg_catalog.array_to_string(c.reloptions || "
-						   "array(select 'toast.' || x from pg_catalog.unnest(tc.reloptions) x), ', ')\n"
-						   : "''"),
-						  oid);
-	}
-	else
-	{
-		appendPQExpBuffer(&buf,
-						  "SELECT c.relchecks, c.relkind, c.relhasindex, c.relhasrules, "
-						  "c.relhastriggers, false, false, c.relhasoids, "
-						  "false as relispartition, %s, c.reltablespace, "
-						  "CASE WHEN c.reloftype = 0 THEN '' ELSE c.reloftype::pg_catalog.regtype::pg_catalog.text END, "
-						  "c.relpersistence\n"
-						  "FROM pg_catalog.pg_class c\n "
-						  "LEFT JOIN pg_catalog.pg_class tc ON (c.reltoastrelid = tc.oid)\n"
-						  "WHERE c.oid = '%s';",
-						  (verbose ?
-						   "pg_catalog.array_to_string(c.reloptions || "
-						   "array(select 'toast.' || x from pg_catalog.unnest(tc.reloptions) x), ', ')\n"
-						   : "''"),
-						  oid);
-	}
 
 	res = PSQLexec(buf.data);
 	if (!res)
@@ -1761,8 +1656,7 @@ describeOneTableDetails(const char *schemaname,
 	tableinfo.reloftype = (strcmp(PQgetvalue(res, 0, 11), "") != 0) ?
 		pg_strdup(PQgetvalue(res, 0, 11)) : NULL;
 	tableinfo.relpersistence = *(PQgetvalue(res, 0, 12));
-	tableinfo.relreplident = (pset.sversion >= 90400) ?
-		*(PQgetvalue(res, 0, 13)) : 'd';
+	tableinfo.relreplident = *(PQgetvalue(res, 0, 13));
 	if (pset.sversion >= 120000)
 		tableinfo.relam = PQgetisnull(res, 0, 14) ?
 			NULL : pg_strdup(PQgetvalue(res, 0, 14));
@@ -1781,8 +1675,6 @@ describeOneTableDetails(const char *schemaname,
 		char	   *footers[3] = {NULL, NULL, NULL};
 
 		printfPQExpBuffer(&buf, "/* %s */\n", _("Get sequence information"));
-		if (pset.sversion >= 100000)
-		{
 			appendPQExpBuffer(&buf,
 							  "SELECT pg_catalog.format_type(seqtypid, NULL) AS \"%s\",\n"
 							  "       seqstart AS \"%s\",\n"
@@ -1804,30 +1696,6 @@ describeOneTableDetails(const char *schemaname,
 							  "FROM pg_catalog.pg_sequence\n"
 							  "WHERE seqrelid = '%s';",
 							  oid);
-		}
-		else
-		{
-			appendPQExpBuffer(&buf,
-							  "SELECT 'bigint' AS \"%s\",\n"
-							  "       start_value AS \"%s\",\n"
-							  "       min_value AS \"%s\",\n"
-							  "       max_value AS \"%s\",\n"
-							  "       increment_by AS \"%s\",\n"
-							  "       CASE WHEN is_cycled THEN '%s' ELSE '%s' END AS \"%s\",\n"
-							  "       cache_value AS \"%s\"\n",
-							  gettext_noop("Type"),
-							  gettext_noop("Start"),
-							  gettext_noop("Minimum"),
-							  gettext_noop("Maximum"),
-							  gettext_noop("Increment"),
-							  gettext_noop("yes"),
-							  gettext_noop("no"),
-							  gettext_noop("Cycles?"),
-							  gettext_noop("Cache"));
-			appendPQExpBuffer(&buf, "FROM %s", fmtId(schemaname));
-			/* must be separate because fmtId isn't reentrant */
-			appendPQExpBuffer(&buf, ".%s;", fmtId(relationname));
-		}
 
 		res = PSQLexec(buf.data);
 		if (!res)
@@ -2045,10 +1913,7 @@ describeOneTableDetails(const char *schemaname,
 		appendPQExpBufferStr(&buf, ",\n  (SELECT c.collname FROM pg_catalog.pg_collation c, pg_catalog.pg_type t\n"
 							 "   WHERE c.oid = a.attcollation AND t.oid = a.atttypid AND a.attcollation <> t.typcollation) AS attcollation");
 		attcoll_col = cols++;
-		if (pset.sversion >= 100000)
 			appendPQExpBufferStr(&buf, ",\n  a.attidentity");
-		else
-			appendPQExpBufferStr(&buf, ",\n  ''::pg_catalog.char AS attidentity");
 		attidentity_col = cols++;
 		if (pset.sversion >= 120000)
 			appendPQExpBufferStr(&buf, ",\n  a.attgenerated");
@@ -2461,10 +2326,7 @@ describeOneTableDetails(const char *schemaname,
 							 CppAsString2(CONSTRAINT_EXCLUSION) ") AND "
 							 "condeferred) AS condeferred,\n");
 
-		if (pset.sversion >= 90400)
 			appendPQExpBufferStr(&buf, "i.indisreplident,\n");
-		else
-			appendPQExpBufferStr(&buf, "false AS indisreplident,\n");
 
 		if (pset.sversion >= 150000)
 			appendPQExpBufferStr(&buf, "i.indnullsnotdistinct,\n");
@@ -2569,10 +2431,7 @@ describeOneTableDetails(const char *schemaname,
 								 "pg_catalog.pg_get_indexdef(i.indexrelid, 0, true),\n  "
 								 "pg_catalog.pg_get_constraintdef(con.oid, true), "
 								 "contype, condeferrable, condeferred");
-			if (pset.sversion >= 90400)
 				appendPQExpBufferStr(&buf, ", i.indisreplident");
-			else
-				appendPQExpBufferStr(&buf, ", false AS indisreplident");
 			appendPQExpBufferStr(&buf, ", c2.reltablespace");
 			if (pset.sversion >= 180000)
 				appendPQExpBufferStr(&buf, ", con.conperiod");
@@ -2823,17 +2682,11 @@ describeOneTableDetails(const char *schemaname,
 		PQclear(result);
 
 		/* print any row-level policies */
-		if (pset.sversion >= 90500)
-		{
 			printfPQExpBuffer(&buf, "/* %s */\n",
 							  _("Get row-level policies for this table"));
 			appendPQExpBufferStr(&buf, "SELECT pol.polname,");
-			if (pset.sversion >= 100000)
 				appendPQExpBufferStr(&buf,
 									 " pol.polpermissive,\n");
-			else
-				appendPQExpBufferStr(&buf,
-									 " 't' as polpermissive,\n");
 			appendPQExpBuffer(&buf,
 							  "  CASE WHEN pol.polroles = '{0}' THEN NULL ELSE pg_catalog.array_to_string(array(select rolname from pg_catalog.pg_roles where oid = any (pol.polroles) order by 1),',') END,\n"
 							  "  pg_catalog.pg_get_expr(pol.polqual, pol.polrelid),\n"
@@ -2904,7 +2757,6 @@ describeOneTableDetails(const char *schemaname,
 				printTableAddFooter(&cont, buf.data);
 			}
 			PQclear(result);
-		}
 
 		/* print any extended statistics */
 		if (pset.sversion >= 140000)
@@ -3007,7 +2859,7 @@ describeOneTableDetails(const char *schemaname,
 			}
 			PQclear(result);
 		}
-		else if (pset.sversion >= 100000)
+		else
 		{
 			printfPQExpBuffer(&buf, "/* %s */\n",
 							  _("Get extended statistics for this table"));
@@ -3173,8 +3025,6 @@ describeOneTableDetails(const char *schemaname,
 		}
 
 		/* print any publications */
-		if (pset.sversion >= 100000)
-		{
 			printfPQExpBuffer(&buf, "/* %s */\n",
 							  _("Get publications that publish this table"));
 			if (pset.sversion >= 150000)
@@ -3284,7 +3134,6 @@ describeOneTableDetails(const char *schemaname,
 				printTableAddFooter(&cont, buf.data);
 			}
 			PQclear(result);
-		}
 
 		/* Print publications where the table is in the EXCEPT clause */
 		if (pset.sversion >= 190000)
@@ -3706,7 +3555,7 @@ describeOneTableDetails(const char *schemaname,
 							  "ORDER BY pg_catalog.pg_get_expr(c.relpartbound, c.oid) = 'DEFAULT',"
 							  " c.oid::pg_catalog.regclass::pg_catalog.text;",
 							  oid);
-		else if (pset.sversion >= 100000)
+		else
 			appendPQExpBuffer(&buf,
 							  "SELECT c.oid::pg_catalog.regclass, c.relkind,"
 							  " false AS inhdetachpending,"
@@ -3716,14 +3565,6 @@ describeOneTableDetails(const char *schemaname,
 							  "ORDER BY pg_catalog.pg_get_expr(c.relpartbound, c.oid) = 'DEFAULT',"
 							  " c.oid::pg_catalog.regclass::pg_catalog.text;",
 							  oid);
-		else
-			appendPQExpBuffer(&buf,
-							  "SELECT c.oid::pg_catalog.regclass, c.relkind,"
-							  " false AS inhdetachpending, NULL\n"
-							  "FROM pg_catalog.pg_class c, pg_catalog.pg_inherits i\n"
-							  "WHERE c.oid = i.inhrelid AND i.inhparent = '%s'\n"
-							  "ORDER BY c.oid::pg_catalog.regclass::pg_catalog.text;",
-							  oid);
 
 		result = PSQLexec(buf.data);
 		if (!result)
@@ -3964,11 +3805,7 @@ describeRoles(const char *pattern, bool verbose, bool showSystem)
 		ncols++;
 	}
 	appendPQExpBufferStr(&buf, "\n, r.rolreplication");
-
-	if (pset.sversion >= 90500)
-	{
 		appendPQExpBufferStr(&buf, "\n, r.rolbypassrls");
-	}
 
 	appendPQExpBufferStr(&buf, "\nFROM pg_catalog.pg_roles r\n");
 
@@ -4023,7 +3860,6 @@ describeRoles(const char *pattern, bool verbose, bool showSystem)
 		if (strcmp(PQgetvalue(res, i, (verbose ? 9 : 8)), "t") == 0)
 			add_role_attribute(&buf, _("Replication"));
 
-		if (pset.sversion >= 90500)
 			if (strcmp(PQgetvalue(res, i, (verbose ? 10 : 9)), "t") == 0)
 				add_role_attribute(&buf, _("Bypass RLS"));
 
@@ -4514,19 +4350,6 @@ listPartitionedTables(const char *reltypes, const char *pattern, bool verbose)
 	const char *tabletitle;
 	bool		mixed_output = false;
 
-	/*
-	 * Note: Declarative table partitioning is only supported as of Pg 10.0.
-	 */
-	if (pset.sversion < 100000)
-	{
-		char		sverbuf[32];
-
-		pg_log_error("The server (version %s) does not support declarative table partitioning.",
-					 formatPGVersionNumber(pset.sversion, false,
-										   sverbuf, sizeof(sverbuf)));
-		return true;
-	}
-
 	/* If no relation kind was selected, show them all */
 	if (!showTables && !showIndexes)
 		showTables = showIndexes = true;
@@ -5034,16 +4857,6 @@ listEventTriggers(const char *pattern, bool verbose)
 	static const bool translate_columns[] =
 	{false, false, false, true, false, false, false};
 
-	if (pset.sversion < 90300)
-	{
-		char		sverbuf[32];
-
-		pg_log_error("The server (version %s) does not support event triggers.",
-					 formatPGVersionNumber(pset.sversion, false,
-										   sverbuf, sizeof(sverbuf)));
-		return true;
-	}
-
 	initPQExpBuffer(&buf);
 
 	printfPQExpBuffer(&buf, "/* %s */\n", _("Get matching event triggers"));
@@ -5113,16 +4926,6 @@ listExtendedStats(const char *pattern, bool verbose)
 	PGresult   *res;
 	printQueryOpt myopt = pset.popt;
 
-	if (pset.sversion < 100000)
-	{
-		char		sverbuf[32];
-
-		pg_log_error("The server (version %s) does not support extended statistics.",
-					 formatPGVersionNumber(pset.sversion, false,
-										   sverbuf, sizeof(sverbuf)));
-		return true;
-	}
-
 	initPQExpBuffer(&buf);
 
 	printfPQExpBuffer(&buf, "/* %s */\n", _("Get matching extended statistics"));
@@ -5352,7 +5155,6 @@ listCollations(const char *pattern, bool verbose, bool showSystem)
 					  gettext_noop("Schema"),
 					  gettext_noop("Name"));
 
-	if (pset.sversion >= 100000)
 		appendPQExpBuffer(&buf,
 						  "  CASE c.collprovider "
 						  "WHEN " CppAsString2(COLLPROVIDER_DEFAULT) " THEN 'default' "
@@ -5361,10 +5163,6 @@ listCollations(const char *pattern, bool verbose, bool showSystem)
 						  "WHEN " CppAsString2(COLLPROVIDER_ICU) " THEN 'icu' "
 						  "END AS \"%s\",\n",
 						  gettext_noop("Provider"));
-	else
-		appendPQExpBuffer(&buf,
-						  "  'libc' AS \"%s\",\n",
-						  gettext_noop("Provider"));
 
 	appendPQExpBuffer(&buf,
 					  "  c.collcollate AS \"%s\",\n"
@@ -6688,16 +6486,6 @@ listPublications(const char *pattern)
 	printQueryOpt myopt = pset.popt;
 	static const bool translate_columns[] = {false, false, false, false, false, false, false, false, false, false};
 
-	if (pset.sversion < 100000)
-	{
-		char		sverbuf[32];
-
-		pg_log_error("The server (version %s) does not support publications.",
-					 formatPGVersionNumber(pset.sversion, false,
-										   sverbuf, sizeof(sverbuf)));
-		return true;
-	}
-
 	initPQExpBuffer(&buf);
 
 	printfPQExpBuffer(&buf, "/* %s */\n", _("Get matching publications"));
@@ -6835,16 +6623,6 @@ describePublications(const char *pattern)
 	PQExpBufferData title;
 	printTableContent cont;
 
-	if (pset.sversion < 100000)
-	{
-		char		sverbuf[32];
-
-		pg_log_error("The server (version %s) does not support publications.",
-					 formatPGVersionNumber(pset.sversion, false,
-										   sverbuf, sizeof(sverbuf)));
-		return true;
-	}
-
 	has_pubsequence = (pset.sversion >= 190000);
 	has_pubtruncate = (pset.sversion >= 110000);
 	has_pubgencols = (pset.sversion >= 180000);
@@ -7095,16 +6873,6 @@ describeSubscriptions(const char *pattern, bool verbose)
 		false, false, false, false, false, false, false, false, false, false,
 	false, false, false, false, false, false, false};
 
-	if (pset.sversion < 100000)
-	{
-		char		sverbuf[32];
-
-		pg_log_error("The server (version %s) does not support subscriptions.",
-					 formatPGVersionNumber(pset.sversion, false,
-										   sverbuf, sizeof(sverbuf)));
-		return true;
-	}
-
 	initPQExpBuffer(&buf);
 
 	printfPQExpBuffer(&buf, "/* %s */\n", _("Get matching subscriptions"));
-- 
2.50.1 (Apple Git-155)


--2xrO7hiVfr8aWtYg
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment; filename=v4-0004-run-pgindent.patch



^ permalink  raw  reply  [nested|flat] 968+ messages in thread


end of thread, other threads:[~2026-04-17 18:34 UTC | newest]

Thread overview: 968+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-14 09:59 [PATCH] Teach REPACK to upgrade its lock safely. Antonin Houska <[email protected]>
2026-04-17 18:34 [PATCH v4 3/4] psql: bump minimum supported version to v10 Nathan Bossart <[email protected]>

This inbox is served by agora; see mirroring instructions
for how to clone and mirror all data and code used for this inbox